import {messageType} from "@src/pages/home/news/privateChat"

interface messagesCreateType {
    otherUserEmail: string,
    recipientEmail: string,
    message: messageType,
}


//获取 所有聊天记录
export const getLocalStorageChatHistory = (): messagesCreateType[] => {
    const localStorageMessages = localStorage.getItem('chatHistory')
    if (localStorageMessages == null) {
        return []
    } else {
        //所有聊天记录
        return JSON.parse(localStorageMessages)
    }
}
//获取指定 用户的聊天记录
export const getChatHistory = (recipientEmail: string, otherUserEmail: string) => {
    let messages = getLocalStorageChatHistory()
    messages.sort((a, b) => b.message.time - a.message.time);
    messages = messages.filter((item) => ((item.recipientEmail == recipientEmail) && (item.otherUserEmail == otherUserEmail)))
    console.log(messages)
    //获取指定 用户的聊天记录
    return messages
}

//添加聊天记录
export const AddChatHistory = (messagesCreate: messagesCreateType) => {
    const messages = getLocalStorageChatHistory()
    messages.push(messagesCreate)
    localStorage.setItem('chatHistory', JSON.stringify(messages))
}
//添加聊天历史
export const AddChatHistoryList = (messages: messagesCreateType[]) => {
    const message = getLocalStorageChatHistory()
    const newMessage = message.concat(messages)
    const uniqueArr = Array.from(
        newMessage.reduce((map, item) => {
            if (!map.has(item.message.time)) {
                map.set(item.message.time, item);
            }
            return map;
        }, new Map()).values()
    );
    localStorage.setItem('chatHistory', JSON.stringify(uniqueArr))
}